<?php


class XunJian_BaoZhuang extends CI_Controller
{
    private $appId;
    private $appSecret;
    private $compName;
    private $weiXinConfigTableName;
    private $proLineTable;
    private $classesData;

    function __construct()
    {
        parent::__construct();
        $this->compName = "容百科技";
        $this->weiXinConfigTableName = "weixininfo_rb";
        $this->proLineTable = "gzrb_productline";
        $data = $this->Data_model->get_single_data(array("type" => "access_token","compname" => $this->compName),$this->weiXinConfigTableName);
        $this->appId = $data['corpid'];
        $this->appSecret = $data['corpsecret'];
        $this->classesData = array("0" => array("val" => "0","valName" => "夜班"),
            "1" => array("val" => "1","valName" => "白班"));;
    }

    function index(){
        $this->load->view("XunJianChose");
    }

    /*
     * 获取巡检单据类型
     * Type
     * baoZhuang_SBYJDJB 设备一级点检表
     * baoZhuang_SBEJDJB 设备二级点检表
     * baoZhuang_HJCTJLB 环境除铁记录表
     * baoZhuang_SJZBLJCB 烧结装钵量检查表
     * baoZhuang_YLYHLJCJLB 窑炉氧含量监测记录表
     * baoZhuang_YLPQKQLJLB 窑炉排气口清理记录表
     */
    function XunJianType(){
        $get = $this->input->get();
        $signPackage = $this->getSignPackage();
        $pathArr = explode("_",$get['Type']);
        $signPackage['process'] = $pathArr[0];
        $signPackage['tableName'] = $pathArr[1];
        $signPackage['lineData'] = $this->getLine();
        $signPackage['username'] = $get['username'];
        $signPackage['userid'] = $get['userid'];
        $this->load->view($pathArr[0]."/".$pathArr[1],$signPackage);
    }
    /*
     * 单据提交成功
     */
    function submitSuccess(){
        $userid = $_REQUEST["userid"];
        $data = array(
            "userid" => $userid
        );
        $this->load->view("SubmitSuccess",$data);
    }

    /*
     * 环境除铁记录表-数据新增
     */
    function addHJCTJLB(){
        $post = $this->input->post();
        $post['createTime'] = time();
        $post['year'] = date("Y",time());
        $post['month'] = date("m",time());
        $post['day'] = date("d",time());
        $post['hour'] = date("H",time());
        $this->Data_model->add_data($post,"gzrb_baozhuang_hjctjlb");
    }

    /*
     * 环境除铁记录表-数据列表
     */
    public function dataAllList_HJCTJLB(){
        $get = $this->input->get();
        $where = array("status" => 1);
        $productLine = "";
        $classes = "";
        if(isset($get['productLine']) and strlen($get['productLine']) > 0){
            $productLine = $get['productLine'];
            $where['productLine'] = $productLine;
        }
        if(isset($get['classes']) and strlen($get['classes']) > 0){
            $classes = $get['classes'];
            $where['classes'] = $classes;
        }
        $listAll = array();
        $listall = $this->Data_model->get_data($where,'','id desc',0,0,"gzrb_baozhuang_hjctjlb");
        $new_list = array();
        $i = 1;
        foreach ($listall as $value) {
            $value['lid'] = $i;
            $i++;
            $d = $this->Data_model->get_single_data(array('lineId' => $value['productLine']),$this->proLineTable);
            $value['productLine'] = $d['lineName'];
            array_push($new_list, $value);
        }
        $info['site_template'] = 'rbReport';
        $info['site_templateurl'] = base_url('/html').'/'.$info['site_template'];
        $lineData = $this->getLine();
        $res = array(
            'list'    => $new_list,
            'config'  => $info,
            'lineData'=> $lineData,
            'productLine' => $productLine,
            'classesData' => $this->classesData,
            'classes' => $classes
        );
        $this->load->view('rbReport/yiPei_HJCTJLBList',$res);
    }

    /*
     * 环境除铁记录表-单条数据
     */
    public function getSingleContent_HJCTJLB(){
        $get = $this->input->get();
        $id = $get['id'];
        $data = $this->Data_model->get_single_data(array('id' => $id),"gzrb_baozhuang_hjctjlb");
        $data["createTime"] = date("Y-m-d H:i:s",$data['createTime']);
        echo json_encode($data);
    }


    /*
     * 检查当天线体提报的巡检数据是否重复
     */
    function checkRepeat($productLine, $process = "baozhuang", $type){
        $tablename = "gzrb_".$process."_".$type;
        $year = date("Y",time());
        $month = date("m",time());
        $day = date("d",time());
        $data = $this->Data_model->get_single_data(array("productLine" => $productLine,
            "year" => $year,
            "month" => $month,
            "day" => $day), $tablename);
    }
    /*
     * 获取所有的产线信息
     */
    function getLine(){
        $data = $this->Data_model->get_data(array("status" => 1),"","",0,0,$this->proLineTable);
        return $data;
    }

    /*
     * 获取微信秘钥
     */
    public function getSignPackage(){
        $jsapiTicket = $this->getJsApiTicket();
        // 注意 URL 一定要动态获取，不能 hardcode.
        $protocol = (!empty($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] !== "off" || $_SERVER["SERVER_PORT"] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        //var_dump($jsapiTicket);
        $signature = sha1($string);

        $signPackage = array(
            "appId"     => $this->appId,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string,
            "createTime"=> time()
        );
        return $signPackage;
    }

    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    private function getJsApiTicket() {
        // jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
        //$data = json_decode(file_get_contents("weixinJS/jsapi_ticket.json"));
        $data = $this->Data_model->get_single_data(array("type" => "jsapi_ticket","compname" => $this->compName),$this->weiXinConfigTableName);
//        var_dump("输出$data");
//        var_dump($data);
//        var_dump(time());
        if ($data["time"] < time() || $data === null) {
            $accessToken = $this->get_access_token();
            // 如果是企业号用以下 URL 获取 ticket
            $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
            //$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
            $res = json_decode($this->http_request_json($url));

            $ticket = $res->ticket;
            if ($ticket) {
                if($data === null){
                    $this->Data_model->add_data(array("compname" => $this->compName,"type" => "jsapi_ticket","jsapi_ticket" => $ticket),$this->weiXinConfigTableName);
                }else{
                    $this->Data_model->update_data(array("type" => "jsapi_ticket"),array("time" => time() + 7000,"jsapi_ticket" => $ticket),$this->weiXinConfigTableName);
                }
                /*
                        $data->expire_time = time() + 7000;
                $data->jsapi_ticket = $ticket;
                $fp = fopen("weixinJS/jsapi_ticket.json", "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
                 *
                 */
            }
        } else {
            $ticket = $data["jsapi_ticket"];
        }
        return $ticket;
    }

    function get_access_token(){
        $result = $this->Data_model->get_single_data(array("compname"=>$this->compName,"type"=>"access_token"),$this->weiXinConfigTableName);
        if($result["time"] < time() || $result === null){
            $corpid = $result["corpid"];
            $corpsecret = $result["corpsecret"];
            if($result === null){
                $corpid = $this->appId;
                $corpsecret = $this->appSecret;
            }
            $url="https://qyapi.weixin.qq.com/cgi-bin/gettoken?&corpid=".$corpid."&corpsecret=".$corpsecret;

            $json=self::http_request_json($url);//这个地方不能用file_get_contents
            $data=json_decode($json,true);
            if(isset($data["access_token"])){
                if($result === null){
                    $this->Data_model->add_data(array("compname"=>$this->compName,"corpid" => $this->appId,"corpsecret" => $this->appSecret,"type"=>"access_token","access_token" => $data["access_token"]),$this->weiXinConfigTableName);
                }else{
                    $this->Data_model->update_data(array("compname"=>$this->compName,"type"=>"access_token"),array("access_token" => $data["access_token"],"time" => time()+7000),$this->weiXinConfigTableName);
                }
                $access_token = $data["access_token"];
            }else{
                return "获取access_token错误";
            }
        }else{
            $access_token = $result["access_token"];
        }
        return $access_token;
    }

    function http_request_json($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}